<template>
	<!-- pages/address_edit/address_edit.wxml -->
	<view class="address-edit">
		<!-- 头部导航 -->
		<u-navbar title="收货地址" :title-bold="true" title-color="#000" :border-bottom="false" custom-class="home-bg" :background="{ background: 'transparent' }"></u-navbar>

		<view class="text-top">{{ title }}</view>

		<form @submit="formSubmit" report-submit="true">
			<view class="form ml20">
				<view class="form-item row">
					<view class="label">名称</view>
					<input class="ml10" v-model="addressObj.receiverName" name="receiverName" type="text" placeholder="请填写收货人姓名" />
				</view>
				<view class="form-item row">
					<view class="label flex">
						电话
						<view style="font-size: 24rpx; color: #333333; margin: 0 0 7rpx 10rpx">
							+86
							<u-icon name="arrow-down-fill" size="22" style="margin-left: 5rpx"></u-icon>
						</view>
					</view>
					<input class="ml10" name="phoneNumber" v-model="addressObj.phoneNumber" type="number" placeholder="请填写手机号码" />
				</view>
				
				<view @click="showRegion = true">
					<view class="form-item row">
						<view class="label">所在地区</view>
						<input class="ml10" name="region" v-model="region" type="text" placeholder="请选择省、市、区" />
						<image class="icon-sm ml10" src="/static/images/arrow_right.png" />
					</view>
				</view>
				
				<view>
					<u-field
						v-model="addressObj.address"
						type="textarea"
						label="详细地址"
						placeholder="请填写小区、街道、门牌号等信息"
						:field-style="{ flex: 1, 'margin-left': '20rpx', height: '160rpx' }"
					/>
					<!-- <view class="form-item row" style="height: 200rpx;">					 -->
					<!-- <view class="label mt20" style="align-self: flex-start;">详细地址</view> -->
					<!-- <textarea name="address" style="height: 160rpx;padding: 20rpx 20rpx 20rpx 30rpx;" v-model="addressObj.address"  @input="textareaChange" placeholder="请填写小区、街道、门牌号等信息" auto-blur /> -->
					<!-- </view> -->
				</view>
			</view>
			<view class="mt10 mb10 check-wrap">
				<radio-group class="row" @click="ChangeIsDefault">
					<radio id="checkbox" style="border-radius: 50%; transform: scale(0.7)" :checked="addressObj.isDefault == 2 ? true : false" color="#FF2C3C" />
					<label for="checkbox">
						<text>设置为默认</text>
					</label>
				</radio-group>
			</view>

			<view class="flex flex-center">
				<button class="buttom-btn" form-type="submit">保存</button>
			</view>
		</form>
		<u-select v-model="showRegion" mode="mutil-column-auto" @confirm="regionChange" :list="lists"></u-select>
	</view>
</template>

<script>
import user from '@/api/user.js';
import area from '@/utils/area';
import { phoneValidate } from '@/utils/validate.js';
export default {
	data() {
		return {
			addressObj: {
				receiverName: '',
				phoneNumber: '',
				province: '',
				city: '',
				district: '',
				address: '',
				isDefault: 1
			},
			region: '',
			addressId: '',
			defaultRegion: ['广东省', '广州市', '番禺区'],
			defaultRegionCode: '440113',
			showRegion: false,
			lists: [],
			title: ''
		};
	},
	props: {},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: function (options) {
		this.addressId = parseInt(options.id);
		if (options.id) {
			this.title = '编辑地址';
			this.getOneAddressFun();
		} else {
			this.title = '添加地址';
			this.getWxAddressFun();
		}
		this.$nextTick(() => {
			this.lists = area;
		});
	},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		uni.removeStorageSync('wxAddress');
	},

	methods: {
		async formSubmit(e) {
			let { value } = e.detail;
			let {
				addressObj: { province_id, city_id, district_id, isDefault, address },
				addressId
			} = this;
			value.address = address;
			if (!value.receiverName)
				return this.$toast({
					title: '请填写收货人姓名'
				});
			if (!value.phoneNumber)
				return this.$toast({
					title: '请填写手机号码'
				});
			if (!phoneValidate(value.phoneNumber))
				return this.$toast({
					title: '手机号码填写有误'
				});
			if (!value.region)
				return this.$toast({
					title: '请选择省、市、区'
				});
			if (!value.address)
				return this.$toast({
					title: '请填写小区、街道、门牌号等信息'
				});
			value.province_id = parseInt(province_id);
			value.city_id = parseInt(city_id);
			value.district_id = parseInt(district_id);
			value.isDefault = isDefault;
			value.id = addressId;
			delete value.region;

			if (addressId) {
				//修改
				const res = await user.setAddress({
					id: addressId,
					address: this.region + '-' + value.address,
					receiverName: value.receiverName,
					phoneNumber: value.phoneNumber
				});
				if (value.isDefault == 2) {
					await this.radioChange(addressId);
				}
				uni.showToast({
					title: '修改地址成功',
					icon: 'success',
					duration: 2000
				});

				uni.navigateBack();
			} else {
				//添加
				const res = await user.addAppadd({
					address: this.region + '-' + value.address,
					receiverName: value.receiverName,
					phoneNumber: value.phoneNumber,
					isDefault: value.isDefault
				});
				uni.showToast({
					title: '新增地址成功',
					icon: 'success',
					duration: 2000
				});
				uni.navigateBack({
					url: '/pages/user_address/user_address'
				});
			}
		},
		//默认地址
		async radioChange(id) {
			const res = await user.setDefaultByAddress(id);
			uni.showToast({
				title: '修改地址成功',
				icon: 'success',
				duration: 2000
			});
		},
		regionChange(region) {
			this.addressObj.province_id = region[0].value;
			this.addressObj.city_id = region[1].value;
			this.addressObj.district_id = region[2].value;
			this.region = region[0].label + ' ' + region[1].label + ' ' + region[2].label;
		},

		ChangeIsDefault: function (e) {
			if (this.addressObj.isDefault == 1) {
				this.addressObj.isDefault = 2;
			} else {
				this.addressObj.isDefault = 1;
			}
		},

		textareaChange: function (e) {
			this.addressObj.address = e.detail.value;
		},

		//回显
		getOneAddressFun() {
			user.getAppaddId(this.addressId)
				.then((res) => {
					this.addressObj = res.data;
					const parts = res.data.address.split('-') || ['', ''];
					this.region = parts[0];
					this.addressObj.address = parts[1];

					if (parts.length > 2) {
						let str = '';
						for (var i = 2; i < parts.length; i++) {
							str = str + '-' + parts[i];
						}
						this.addressObj.address += str;
					}
				})
				.catch((erro) => {
					console.log(erro);
				});
		},

		getWxAddressFun() {
			let wxAddress = uni.getStorageSync('wxAddress');
			if (!wxAddress) return;
			wxAddress = JSON.parse(wxAddress);
			let { userName: receiverName, telNumber: phoneNumber, provinceName: province, cityName: city, detailInfo: address } = wxAddress;
			let district = wxAddress.countryName || wxAddress.countyName;
			hasRegionCode({
				province,
				city,
				district
			}).then((res) => {
				if (res.code == 1) {
					if (res.data.province && res.data.city && res.data.district) {
						this.addressObj.province_id = res.data.province;
						this.addressObj.city_id = res.data.city;
						this.addressObj.district_id = res.data.district;
						this.region = `${province} ${city} ${district}`;
					}
					this.addressObj.receiverName = receiverName;
					this.addressObj.phoneNumber = phoneNumber;
					this.addressObj.address = address;
				}
			});
		}
	}
};
</script>
<style lang="scss" scoped>
.flex {
	display: flex;
}
.align-center {
	align-items: center;
}
.flex-center {
	justify-content: center;
}
.flex-between {
	justify-content: space-between;
}
.flex-column {
	flex-direction: column;
}
.text-top {
	width: 224rpx;
	height: 44rpx;
	font-family: PingFang SC, PingFang SC;
	font-weight: 500;
	font-size: 32rpx;
	color: #333333;
	text-align: left;
	font-style: normal;
	text-transform: none;
	margin: 30rpx 40rpx;
}
.buttom-btn {
	margin-top: 200rpx;
	width: 354rpx;
	height: 60rpx;
	line-height: 60rpx;
	background: #f05a39;
	border-radius: 46rpx 46rpx 46rpx 46rpx;
	font-weight: 500;
	font-size: 32rpx;
	color: #ffffff;
}

.address-edit {
	padding-top: 10rpx;
	.form {
		flex: 1;
		.form-item {
			padding: 0 24rpx;
			height: 80rpx;
			&:not(:nth-of-type(3)) {
				border-bottom: $-solid-border;
			}
			.label {
				width: 150rpx;
			}
			input {
				height: 100%;
				flex: 1;
			}
		}
	}
	.check-wrap {
		padding: 20rpx;
	}
	.my-btn {
		margin: 30rpx 26rpx;
		text-align: center;
	}
}

van-field view {
	height: 100%;
}

van-field textarea {
	height: 100% !important;
	padding-top: 10rpx !important;
}

.van-cell {
	padding: 20rpx !important;
}

.van-field__body--textarea,
.van-field__input {
	margin-left: 15rpx;
}
</style>
